<?php


namespace app\stackbylinklist;


class Stack
{
    private $header;        // 头节点
    function __construct($data) {
        $this->header = new Node($data);
    }
    // 判断栈是否为空
    public function isEmpty()
    {
        return $this->header->next === null;
    }
    // 入栈，插入新的栈顶节点
    public function push($element)
    {
        $node = new Node($element);
        $current = $this->header;
        while (!is_null($current->next)){
            $current = $current->next;
        }
        $current->next = $node;
        return true;
    }
    // 出栈，删除栈顶元素
    public function pop()
    {
        if ($this->isEmpty()) { // 栈为空
            return false;
        }
        $current = $this->header;
        while (!is_null($current->next->next)){
            $current = $current->next;
        }
        $current->next = null;
        return true;
    }
    // 清空栈
    public function clear() {
        $this->header = null;
    }
    // 显示栈中的元素
    public function show() {
        $current = $this->header;
        if ($this->isEmpty()) {
            echo "空！";
        }
        while ($current->next != null) {
            echo $current->next->data . PHP_EOL;
            $current = $current->next;
        }
    }
}